import Taro, { Component } from "@tarojs/taro";
import { connect } from "@tarojs/redux";
import { View, Text } from "@tarojs/components";
import { AtSearchBar, AtButton, AtActionSheet, AtActionSheetItem, AtModal, AtModalContent, AtModalHeader, AtModalAction, AtFloatLayout } from "taro-ui";
import { $Req } from "@utils";
import qs from "qs";
import QR from 'wxmp-qrcode'
import "./index.scss";

@connect(
  ({ userModel }) => ({
    userModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "我的订单",
  };

  constructor(props) {
    super(...arguments);
    const { type } = this.$router.params;
    const title = ["全部订单", "待付款", "待收货", "已完成"];
    wx.setNavigationBarTitle({
      title: title[type],
    });
    const apiMap = [
      "/order/getUserOrder?ordersState=0",
      "/order/getUserOrder?ordersState=20000",
      "/order/getUserOrder?ordersState=20002",
      "/order/getUserOrder?ordersState=20003",
    ];
    const apiUrl = apiMap[type];
    this.state = {
      type,
      apiUrl,
      searchVal: "",
      list: [],
      showPayModel: false,
      currOrder: {},
      showAliPayModel: false,
      jfData: {},
      expressInfo: {},
      layoutShow: false,
      aliPayOk: false
    };
  }

  componentDidShow() {
    let payFlag = Taro.getStorageSync("syPay");
    let ordersNo = Taro.getStorageSync("ordersNo");
    if (payFlag) {
      return this.syPay(ordersNo);
    }

    this.getGoodsOrder();
    this.getJfNum();
    this.setState({
      aliPayOk: false,
      showPayModel: false,
      showAliPayModel: false
    })
  }

  // 获取积分数量
  async getJfNum() {
    let { data } = await $Req({
      type: "get",
      url: "/indexUser/getUserIntegral",
      data: {}
    });
    if (!data) return;

    this.setState({
      jfData: data
    })
  }

  // 获取产品订单
  async getGoodsOrder() {
    const {
      userModel: { userInfo },
    } = this.props;

    let { data } = await $Req({
      type: "GET",
      url: this.state.apiUrl,
      data: {
        userId: userInfo.userId,
      },
    });
    if (!data) return;
    data.map(item => {
      item.orderDetailList[0].vip = item.vipOrder;
    })
    this.setState({
      list: data,
    });
  }

  // 再次购买
  zcBuy(list, finalAmount) {
    list.forEach(el => {
      el.skuDetail = "null",
        el.id = el.skuId
      delete el.orderDetailId
      delete el.ordersId
      delete el.ordersNo
    });

    // 结算
    Taro.navigateTo({
      url: `/pages/order/confirm/index?orderList=${JSON.stringify(list)}&totalMoney=${finalAmount}&totalProduct=${list.length}`,
    });
  }
   // 积分支付
  async getJFPay(ordersNo, totalMoney) {
    const {
      userModel: { userInfo },
    } = this.props;
    let { data } = await $Req({
      type: "post",
      url: `/order/useIntegralPay?${qs.stringify({
        ordersNo,
        userId: userInfo.userId,
        useIntegral: totalMoney
      })}`,
    });
    if (!data) return;

    this.getGoodsOrder();
    Taro.showToast({
      title: "支付成功"
    })
  }

  // 支付宝支付签名
  async getNativePaySign(orderId, price) {
    const {
      userModel: { userInfo },
    } = this.props;
    let { data } = await $Req({
      type: "post",
      url: `/pay/pay?userId=${userInfo.userId}&orderId=${orderId}&amount=${price * 100}&orderType=${1}&payModel=MIC_DISTR_PAY_MODEL_NATIVE&payType=MIC_DISTR_PAY_TYPE_ALIPAY`,
    });
    if (!data) return;

    this.setState({
      showAliPayModel: true
    }, () => {
      QR.draw(data.qrCode, "canvas")

      let Timer = setInterval(() => {
        if (this.state.aliPayOk) {
          clearInterval(Timer);
          this.getGoodsOrder();
          Taro.showToast({
            title: "支付成功"
          })

        } else {
          this.queryPay(orderId, data.checkoutId, price * 100);
        }
      }, 2000)
    })
  }

  // 获取微信支付签名
  async getPaySign(orderId, price) {
    console.log(orderId, price);
    const {
      userModel: { userInfo },
    } = this.props;
    let { code, message, data } = await $Req({
      type: "post",
      url: "/pay/pay?" + qs.stringify({
        userId: userInfo.userId,
        openId: userInfo.openId,
        orderId: orderId,
        // amount: 1,
        amount: price * 100,
        orderType: 1,
        payModel: "MIC_DISTR_PAY_MODEL_MINI_APP",
        payType: "MIC_DISTR_PAY_TYPE_WEBCHAT",
      })
    });
    if (!data) return;
    this.payOrder(data);
  }


  // 查询支付结果
  async queryPay(orderId, checkoutId, amount) {
    let { data } = await $Req({
      type: "get",
      url: `/pay/queryPay`,
      data: {
        payModel:"MIC_DISTR_PAY_MODEL_NATIVE",
        payType:"MIC_DISTR_PAY_TYPE_ALIPAY",
        orderId,
        checkoutId,
        orderType: 1,
        amount
      }
    });
    if (!data) return;
    
    if (data.fundBillList && data.fundBillList.length) {
      this.setState({
        aliPayOk: true,
        showPayModel: false
      })
    }
  }

  // 微信支付
  payOrder(res) {
    Taro.requestPayment({
      appId: res.appId,
      timeStamp: res.timeStamp,
      nonceStr: res.nonceStr,
      signType: res.signType,
      package: res.package,
      paySign: res.paySign,
      success(res) {
        Taro.showToast({
          title: "支付成功",
          icon: "none",
          duration: 1000,
        });
        this.getGoodsOrder();
        Taro.showToast({
          title: "支付成功"
        })
      },
      fail(res) {
        Taro.showToast({
          title: "支付失败",
          icon: "none",
          duration: 1000,
        });
      },
    });
  }

  // 取消订单
  async cancelOrder(ordersNo) {
    let { data } = await $Req({
      type: "GET",
      url: "/order/cancelOrder",
      data: {
        ordersNo
      },
    });
    if (!data) return;
    
    Taro.showToast({
      title: "取消成功!"
    })
    this.getGoodsOrder();
  }

  // 搜索
  async onSearch() {
    const {
      userModel: { userInfo },
    } = this.props;

    let { data } = await $Req({
      type: "GET",
      url: this.state.apiUrl,
      data: {
        userId: userInfo.userId,
        keyWord: this.state.searchVal
      },
    });
    if (!data) return;
    this.setState({
      list: data,
    });
  }

  // 查看快递
  async lookExpress(ordersNo) {
    let { data } = await $Req({
      type: "GET",
      url: "/order/getOrdersLogisticsList",
      data: {
        ordersNo
      },
    });
    if (!data) return;
    
    this.setState({
      expressInfo: data[0],
      layoutShow: true
    })
  }

  // 确认收货
  async okSuccess(ordersNo) {
    let { data } = await $Req({
      type: "GET",
      url: "/order/userConfirmOrderArrival",
      data: {ordersNo},
    });
    if (!data) return;

    Taro.showToast({
      title: "确认收货成功!"
    })
    this.getGoodsOrder();
  }

  async syPay(ordersNo, totalMoney) {

    const {
      userModel: { userInfo },
    } = this.props;

    // 检查支付密码
    let abc = await $Req({
      type: "get",
      url: "/indexUser/checkHavePayPassword",
      data: { userId: userInfo.userId },
    });
    let payFlag = Taro.getStorageSync("syPay");
    
    if (abc.code == 200) {
      if (!payFlag) {
        // 有密码
        if (abc.data) {
          Taro.navigateTo({
            url: `/pages/user/payPwd/index?flag=1&price=${this.state.currOrder.finalAmount}&ordersNo=${ordersNo}`
          })
          return false;
        }
        // 没密码 
        else {
          Taro.navigateTo({
            url: '/pages/user/payPwd/index'
          })
          return false;
        }
      } else {
        Taro.showLoading({
          title: "支付中..."
        })

        var obj = await $Req({
          type: "post",
          url: `/order/usebenefitPay?ordersNo=${ordersNo}`,
          // data: {
          //   payType: 10,
          //   ordersNo: ordersNo,
          // },
        });
        Taro.removeStorageSync("syPay");
        Taro.removeStorageSync("ordersNo");
        if (obj.code != 200) return;
        
        Taro.hideLoading();
        
        Taro.showToast({
          title: "支付成功",
          icon: "none"
        })

        this.getGoodsOrder();
        return false;
      }
    }
  }

  render() {
    return (
      <View className="at-row page-order-index">
        <View className="at-col">
          <View className="at-row search-box">
            <AtSearchBar
              showActionButton
              fixed
              value={this.state.searchVal}
              onChange={(v) => {
                if (v) {
                  this.setState({
                    searchVal: v,
                    layoutShow: false
                  })
                } else {
                  this.getGoodsOrder();
                }
               
              }}
              onClear={
                () => {
                  this.setState({
                    searchVal: ""
                  })
                  this.getGoodsOrder();
                }
              }
              onActionClick={() => {
                this.onSearch();
              }}
            />
          </View>
          <View className="at-row order-box">
            <View className="at-col order-list">
              {this.state.list.map((item) => {
                return (
                  <View className="at-row list-item" key={item.goodsId}>
                    <View className="at-col c1">
                      {item.orderDetailList.map((el, index) => (
                        <View className="at-row r1" style="margin-bottom:10px" key={el.ordersId}
                          onClick={
                            () => {
                              Taro.navigateTo({
                                url: "/pages/mall/detail/index?goodsId=" + el.skuId,
                              });
                            }
                          }
                        >
                          <View className="at-col at-col-4 c11">
                            <image style="width:90px; height:90px;" src={el.skuCoversUrl} />
                          </View>
                          <View className="at-col at-col-6 c12">
                            <View className="at-row">
                              <Text className="title">{el.goodsName}</Text>
                            </View>
                            <View className="at-row">
                              <Text className="specs">
                              {/* {el.skuTitleType}： */}
                                {el.skuTitle}
                              </Text>
                            </View>
                            {
                              item.integralOrder == 1 ?
                              <View className="at-col" style="text-align: left;margin-top: 4PX;">
                                <Text style="color: #ccc; font-size:12PX">积分商品订单</Text>
                              </View>
                              :
                              null
                            }
                            <View className="at-row">
                              <Text className="price">
                        ￥{el.skuCurrPrice}.0元{item.vipOrder*1==1?'':'/积分'}
                              </Text>
                            </View>
                          </View>
                          <View className="at-col at-col-2 c13">
                            {
                              !index ? <Text className="status">{item.ordersName}</Text> : null
                            }
                            <Text className="count">x{el.quantity}</Text>
                              {
                                item.ordersState == "20003" && item.payWay != 2 ?
                                  <View style="margin-top: 40px;" onClick={
                                    (e) => {
                                      e.stopPropagation();
                                      Taro.navigateTo({
                                        url: "/pages/order/index/createFp?details=" + JSON.stringify(item)
                                      })
                                    }
                                  }>
                                    <Text style="border: 1px solid #ccc; color:#ccc; font-size: 12px; padding: 2px 4px; border-radius: 4px;">开发票</Text>
                                  </View>
                                : null
                              }
                            
                          </View>
                        </View>
                      ))}
                      <View className="at-row at-row__justify--end r2">
                        <Text style="padding-right: 8px;">总价￥{item.totalAmount}</Text>
                        {
                          item.useIntegral ?
                            <View>
                              <Text>积分抵扣￥{item.useIntegral}</Text>
                              <Text>需付款￥{item.totalAmount - item.useIntegral}</Text>
                            </View>
                            :
                            null
                        }
                      </View>
                      <View className="at-row at-row__justify--end r3">
                        {/* 关闭订单的 */}
                        {
                          item.ordersState == 20004
                            ?
                            <AtButton
                              type="secondary"
                              circle
                              size="small"
                              className="btn-left"
                              onClick={
                                () => {
                                  this.zcBuy(item.orderDetailList, item.finalAmount);
                                }
                              }
                            >
                              再次购买
                          </AtButton>
                            : null
                        }
                        {/* 待付款 */}
                        {
                          item.ordersState == 20000
                            ?
                            <View class="at-row" style="justify-content:flex-end">
                              <AtButton
                                type="secondary"
                                circle
                                size="small"
                                className="btn-left"
                                onClick={
                                  () => {
                                    this.cancelOrder(item.ordersNo)
                                  }
                                }
                              >
                                取消订单
                              </AtButton>
                              <View style="width:5PX;"></View>
                              <AtButton
                                type="primary"
                                circle
                                size="small"
                                className="btn-right"
                                onClick={
                                  () => {
                                    this.setState({
                                      showPayModel: true,
                                      currOrder: item
                                    })

                                    console.log(item);
                                  }
                                
                                }
                              >
                                结算
                              </AtButton>
                            </View>
                            : null
                        }

                        {/* 已付款 */}
                        {
                          item.ordersState == 20001
                            ?
                            <AtButton
                                type="secondary"
                                circle
                                size="small"
                                className="btn-left"
                                onClick={
                                  () => {
                          

                                    Taro.navigateTo({
                                      url:`/pages/order/refund/index?orderDetails=${JSON.stringify(item)}&type=2`
                                    })

                                  }
                                }
                              >
                                退款
                              </AtButton>
                            : null
                        }
                        {/* 已收货 */}
                        {
                          item.ordersState == 20003
                            ?
                            <View class="at-row" style="justify-content:flex-end">
                              {/* <AtButton
                                type="secondary"
                                circle
                                size="small"
                                className="btn-left"
                                openType="share"
                                onClick={
                                  () => {
                                    this.setState({
                                      currOrder: item
                                    })
                                  }
                                }
                              >
                                分享好友
                                </AtButton> */}
                              <AtButton
                                type="secondary"
                                circle
                                size="small"
                                className="btn-left"
                                onClick={
                                  () => {
                                    this.zcBuy(item.orderDetailList, item.finalAmount);
                                  }
                                }
                              >
                                再次购买
                                </AtButton>
                            </View>
                            : null
                        }

                        {/* 已发货 */}
                        {
                          item.ordersState == 20002
                            ?
                            <View class="at-row" style="justify-content:flex-end">
                              <AtButton
                                type="secondary"
                                circle
                                size="small"
                                className="btn-left"
                                onClick={
                                  () => {
                                    Taro.navigateTo({
                                      url:`/pages/order/refund/index?orderDetails=${JSON.stringify(item)}&type=1`
                                    })
                                  }
                                }
                              >
                                退货
                              </AtButton>
                              <AtButton
                                type="secondary"
                                circle
                                size="small"
                                className="btn-left"
                                onClick={() => {
                                  this.lookExpress(item.ordersNo);
                                }}
                              >
                                查看物流
                              </AtButton>
                              <AtButton
                                type="secondary"
                                circle
                                size="small"
                                className="btn-left"
                                onClick={
                                  () => {
                                    Taro.showModal({
                                      title: '提示',
                                      content: '请先确保已收到包裹，然后确认商品无损坏、无质量问题后再点击确认收货',
                                      confirmText:'我已确认',
                                      success: (res) => {
                                        if (res.confirm) {
                                          this.okSuccess(item.ordersNo);
                                        } else if (res.cancel) {
                                          console.log('用户点击取消')
                                        }
                                      }
                                    });
                                    
                                    
                                  }
                                }
                              >
                                确认收货
                              </AtButton>
                            </View>
                            : null
                        }

                        {/* 退换货 */}
                        {
                          item.ordersState == 20007 || item.ordersState == 20008 || item.ordersState == 20005 || item.ordersState == 20006
                            ?
                            <AtButton
                              type="secondary"
                              circle
                              size="small"
                              className="btn-left"
                              onClick={
                                () => {
                                  
                                  Taro.navigateTo({
                                    url:`/pages/order/refund/index?orderDetails=${JSON.stringify(item)}&type=${ item.ordersState == 20005 || item.ordersState == 20006 ? 2 : 1 }`
                                  })
                                }
                              }
                            >
                              查看退款/退货状态
                          </AtButton>
                            : null
                        }
                      </View>
                    </View>
                  </View>
                );
              })}
            </View>
          </View>
        </View>

        {/* 支付model */}
        <AtActionSheet isOpened={this.state.showPayModel} cancelText='取消' title='支付类型'
          onCancel={() => {
            this.setState({
              showPayModel: false
            })
          }}
          onClose={() => {
            this.setState({
              showPayModel: false
            })
          }}
        >
          <AtActionSheetItem onClick={
            () => {
              this.setState({
                showPayModel: false
              }, () => {
                let { currOrder } = this.state;
                this.getPaySign(currOrder.ordersNo, currOrder.totalAmount)
              })
            }
          }>
            微信支付
          </AtActionSheetItem>
          <AtActionSheetItem onClick={
            () => {
              this.setState({
                showPayModel: false
              }, () => {
                let { currOrder } = this.state;
                this.getNativePaySign(currOrder.ordersNo, currOrder.totalAmount)
              })
            }
          }>
            扫码支付
          </AtActionSheetItem>
          <AtActionSheetItem onClick={
            () => {
              this.setState({
                showPayModel: false
              }, () => {
                let { currOrder } = this.state;
                this.syPay(currOrder.ordersNo, currOrder.totalAmount)
              })
            }
          }>
            收益支付
          </AtActionSheetItem>
          {/* (this.state.jfData.integral >= this.state.currOrder.finalAmount) ||   */}
          {
            (this.state.currOrder.totalAmount == this.state.currOrder.finalAmount && this.state.currOrder.integralOrder) ?
              <AtActionSheetItem onClick={
                () => {
                  this.setState({
                    showPayModel: false
                  }, () => {
                    let { currOrder } = this.state;
                    this.getJFPay(currOrder.ordersNo, currOrder.finalAmount)
                  })
                }
              }>
                积分支付
              </AtActionSheetItem>
            :
            null
          }
        </AtActionSheet>

        {/* 支付宝支付 */}
        <AtModal isOpened={this.state.showAliPayModel}>
          <AtModalHeader>扫码支付</AtModalHeader>
          <AtModalContent>
            {
              this.state.showAliPayModel ?
                <canvas style="margin-left: -24px;" id="canvas" canvas-id="canvas"></canvas>
              :
                null
            }
          </AtModalContent>
          <AtModalAction><Button onClick={
            () => {
              this.setState({
                showAliPayModel: false
              })
            }
          }>确定</Button></AtModalAction>
        </AtModal>

        {/* 快递信息 */}
        <AtFloatLayout isOpened={this.state.layoutShow} title="快递信息" onClose={() => {
          this.setState({
            layoutShow: false
          })
        }}>
          <View style="margin-bottom:5PX;">物流公司：{expressInfo.logisticsName}  </View> 
          <View>快递单号：{expressInfo.deliveryOrdersNo}</View>
        </AtFloatLayout>

      </View>
    );
  }
}
